import { Component, OnInit } from '@angular/core';
import { ScheduleService } from '../service/schedule.service';
import { Schedule, DEGREE, STATUS } from '../model/schedule';
import { Input } from '@angular/core';
import { SimpleChanges } from '@angular/core/src/metadata/lifecycle_hooks';
import { DragulaService } from 'ng2-dragula/components/dragula.provider';

@Component({
  selector: 'app-schedule-list',
  templateUrl: './schedule-list.component.html',
  styleUrls: ['./schedule-list.component.scss']
})
export class ScheduleListComponent implements OnInit {

  @Input() public schedules: Schedule[];
  @Input() public degree: DEGREE;

  constructor(
    public scheduleService: ScheduleService,
    public dragulaService: DragulaService) {
   }

  async ngOnInit() {
    this.dragulaService.drag.subscribe((value) => { 
      return this.onDrag(value);
    });
    this.dragulaService.drop.subscribe((value) => { 
      return this.onDrop(value);
    });
    this.dragulaService.over.subscribe((value) => { 
      return this.onOver(value);
    });
    this.dragulaService.out.subscribe((value) => { 
      return this.onOut(value);
    });
  }

  private onOver(value) { 
    let [e, el, container] = value;
    container = <HTMLElement>container;
    container.classList.add("over");
  }
  private onOut(value) { 
      let [e, el, container] = value;
      container = <HTMLElement>container;
      container.classList.remove("over");
  }
  private onDrag(value) { }
  private async onDrop(value) { 
    // console.log(value)
    let [eName, el, destContainer, fromContainer] = value;
    let id = el.id;
    console.log(destContainer)
    console.log(destContainer.getAttribute("id"))
    
    //应该操作数组
    if (fromContainer.getAttribute("id") == this.degree) { 
      this.pop(id);
    }

    if (destContainer.getAttribute("id") == this.degree) { 
      let schedule = await this.scheduleService.get(id, {});
      schedule.degree = this.degree;
      schedule = await this.scheduleService.update(schedule, {});
      this.push(schedule);
    }
    if (destContainer.getAttribute("id") == 0) { 
      let schedule = await this.scheduleService.get(id, {});
      schedule.status = STATUS.ARCHIVE;
      schedule = await this.scheduleService.update(schedule, {});
    }
  }

  private pop(id: number) { 
    let idx = -1;
    for (let i = 0, ii = this.schedules.length; i < ii; i++) {
      let schedule = this.schedules[i];
      if (schedule.id == id) {
        idx = i;
        break;
      }
    }
    if (idx >= 0) {
      this.schedules.splice(idx, 1);
    }
  }

  private async push(schedule: Schedule) { 
    this.schedules.push(schedule);
  }
}
